package com.example.musicplayer.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.example.musicplayer.R;
import com.example.musicplayer.entity.Music;
import com.example.musicplayer.entity.MusicAndMusicList;
import com.example.musicplayer.entity.MusicList;
import com.example.musicplayer.provider.MusicAndMusicListProvider;
import com.example.musicplayer.provider.MusicListProvider;

import java.util.ArrayList;
import java.util.List;

public class DbUtil {
    private static final int NO_SUCH_MUSIC_LIST = -1; // 没有该歌单

    /**
     * 判断指定歌曲是否在“我喜欢”列表
     *
     * @param musicId 指定需要判断的歌曲的id
     * @return true 如果指定歌曲在“我喜欢”列表，false 如果指定歌曲不在“我喜欢”列表
     */
    public boolean isILike(Context context, String musicId) {
        Cursor cursor;
        int musicListId;
        // 先查询我喜欢歌单的id
        musicListId = getMusicListIdByName(context, "我喜欢");
        if (musicListId == NO_SUCH_MUSIC_LIST) {
            return false;
        }
        // 查询歌曲是否在“我喜欢”歌单中
        cursor = context.getContentResolver().query(
                MusicAndMusicListProvider.CONTENT_URI,
                null,
                MusicAndMusicList.KEY_MUSIC_ID + "=" + musicId + " and " + MusicAndMusicList.KEY_MUSIC_LIST_ID + "=" + musicListId,
                null, null
        );
        if (cursor == null) {
            Toast.makeText(context, "查询出错", Toast.LENGTH_SHORT).show();
            return false;
        }
        // 歌曲不在“我喜欢”歌单中
        if (cursor.getCount() == 0) {
            cursor.close();
            return false;
        }
        // 歌曲在“我喜欢”歌单中
        cursor.close();
        return true;
    }

    /**
     * 根据歌单名称查找歌单id或者判断数据库中有没有指定名称的歌单。
     *
     * @param name 歌单名称
     * @return 歌单的id，如果数据库中没有该歌单，返回-1；如果有，返回歌单的id。
     */
    public int getMusicListIdByName(Context context, String name) {
        Cursor cursor;
        int musicListId = NO_SUCH_MUSIC_LIST;
        cursor = context.getContentResolver().query(
                MusicListProvider.CONTENT_URI,
                null,
                MusicList.MUSIC_LIST_NAME + "=" + "\"" + name + "\"",
                null, null
        );
        if (cursor == null) {
            return musicListId;
        }
        if (cursor.getCount() == 0) {
            cursor.close();
            return musicListId;
        }
        if (cursor.moveToNext()) {
            musicListId = cursor.getInt(cursor.getColumnIndex(MusicList.MUSIC_LIST_ID));
        }
        cursor.close();
        return musicListId;
    }

    /**
     * 将歌曲添加到歌单
     *
     * @param context       上下文对象
     * @param musicID       歌曲id
     * @param musicListName 歌单名称
     * @return 添加成功返回true，添加失败放回false。
     */
    public boolean addMusicToMusicList(Context context, String musicID, String musicListName) {
        int musicListId = getMusicListIdByName(context, musicListName);  // 获取歌单id
        if (musicListId == NO_SUCH_MUSIC_LIST) { // 没有该歌单
            return false;
        } else {
            ContentValues values = new ContentValues();
            values.put(MusicAndMusicList.KEY_MUSIC_ID, musicID);
            values.put(MusicAndMusicList.KEY_MUSIC_LIST_ID, musicListId);
            context.getContentResolver().insert(MusicAndMusicListProvider.CONTENT_URI, values);
            Toast.makeText(context, "已添加到" + musicListName + "列表", Toast.LENGTH_SHORT).show();
            return true;
        }
    }

    /**
     * 根据歌曲id和歌单名称从歌单中删除歌曲
     *
     * @param context       上下文对象
     * @param musicId       指定歌曲id
     * @param musicListName 指定歌单名称
     * @return 如果删除成功返回true，如果删除失败返回false。
     */
    public boolean deleteMusicFromMusicList(Context context, String musicId, String musicListName) {
        int result = context.getContentResolver().delete(
                MusicAndMusicListProvider.CONTENT_URI,
                MusicAndMusicList.KEY_MUSIC_ID + "=" + musicId + " and " +
                        MusicAndMusicList.KEY_MUSIC_LIST_ID + "=" + getMusicListIdByName(context, musicListName),
                null
        );
        if (result > 0) {
            Toast.makeText(context, "已从" + musicListName + "列表移除", Toast.LENGTH_SHORT).show();
            return true;
        } else {
            Toast.makeText(context, "移除失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 获取歌单列表
     *
     * @param context 上下文对象
     * @return 歌单列表
     */
    public List<MusicList> getMusicList(Context context) {
        List<MusicList> musicLists = new ArrayList<>();
        Cursor cursor = context.getContentResolver().query(MusicListProvider.CONTENT_URI, new String[]{MusicList.MUSIC_LIST_ID, MusicList.MUSIC_LIST_NAME}, null, null, null);
        if (cursor == null) {
            return musicLists;
        }
        if (cursor.getCount() == 0) {
            Toast.makeText(context, "数据库中没有歌单", Toast.LENGTH_SHORT).show();
            cursor.close();
            return musicLists;
        }
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex(MusicList.MUSIC_LIST_ID));
            String name = cursor.getString(cursor.getColumnIndex(MusicList.MUSIC_LIST_NAME));
            int count = getMusicCountOfMusicList(context, name);
            if (count == NO_SUCH_MUSIC_LIST) {
                count = 0;
            }
            MusicList musicList = new MusicList(id, name, count);
            musicLists.add(musicList);
        }
        cursor.close();
        // 数据库中没有歌单返回空，否则返回歌单列表
        return musicLists;
    }

    /**
     * 获取歌单中歌曲的数量
     *
     * @param context       上下文对象
     * @param musicListName 指定歌单的名称
     * @return 指定歌单中歌曲的数量
     */
    public int getMusicCountOfMusicList(Context context, String musicListName) {
        int count = 0;
        int musicListId = getMusicListIdByName(context, musicListName);
        if (musicListId == NO_SUCH_MUSIC_LIST) {
            return NO_SUCH_MUSIC_LIST;
        } else {
            Cursor cursor = context.getContentResolver().query(
                    MusicAndMusicListProvider.CONTENT_URI,
                    null,
                    MusicAndMusicList.KEY_MUSIC_LIST_ID + "=" + musicListId,
                    null, null
            );
            if (cursor == null) {
                return count;
            }
            count = cursor.getCount();
            cursor.close();
            return count;
        }
    }

    /**
     * 获取指定歌单中的歌曲
     *
     * @param context       上下文对象
     * @param musicListName 指定歌单的名称
     * @return 指定歌单中的歌曲列表
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public List<Music> getMusicInMusicList(Context context, String musicListName) {
        Cursor cursor;
        List<Music> musics = new ArrayList<>();
        int musicListId = getMusicListIdByName(context, musicListName);
        if (musicListId == NO_SUCH_MUSIC_LIST) {
            return musics;
        } else {
            // 先获取歌曲的id
            cursor = context.getContentResolver().query(
                    MusicAndMusicListProvider.CONTENT_URI,
                    null,
                    MusicAndMusicList.KEY_MUSIC_LIST_ID + "=" + musicListId,
                    null, null
            );
            if (cursor == null) {
                return musics;
            }
            if (cursor.getCount() == 0) {
                cursor.close();
                return musics;
            } else {
                while (cursor.moveToNext()) {
                    // 根据歌曲id获取音乐
                    String musicId = cursor.getString(cursor.getColumnIndex(MusicAndMusicList.KEY_MUSIC_ID));
                    Log.i("==============", musicId);
                    Cursor musicCursor = context.getContentResolver().query(
                            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                            null,
                            MediaStore.Audio.Media._ID + "=" + musicId,
                            null, null
                    );
                    if (musicCursor == null || musicCursor.getCount() == 0) {
                        Log.i("=================", "查询结果为空");
                        return musics;
                    } else {
                        while (musicCursor.moveToNext()) {
                            Music music;
                            String id = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media._ID));
                            String name = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                            String artist = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                            String path = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA));

                            // ======== 获取专辑封面(begin) ===================//
                            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                            try {
                                retriever.setDataSource(path);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            byte[] data = retriever.getEmbeddedPicture();
                            Bitmap bitmap;
                            if (data != null) {
                                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                            } else {
                                BitmapDrawable bitmapDrawable = (BitmapDrawable) context.getDrawable(R.drawable.album);
                                assert bitmapDrawable != null;
                                bitmap = bitmapDrawable.getBitmap();
                            }
                            music = new Music(id, name, artist, path, bitmap);
                            Log.i("===================", music.getName());
                            musics.add(music);
                        }
                    }
                    musicCursor.close();
                }
            }
            cursor.close();
        }
        return musics;
    }

    /**
     * 删除指定名称的歌单
     *
     * @param context       上下文对象
     * @param musicListName 想要删除的歌单名称
     * @return 删除成功返回true，删除失败返回false
     */
    public boolean deleteMusicList(Context context, String musicListName) {
        int musicListId;
        musicListId = getMusicListIdByName(context, musicListName);
        if (musicListId == NO_SUCH_MUSIC_LIST) {
            return false;
        }
        // 删除musicandmusiclist表中所有关于指定歌单的数据
        int deleteMusicInMusicListResult = context.getContentResolver().delete(
                MusicAndMusicListProvider.CONTENT_URI,
                MusicAndMusicList.KEY_MUSIC_LIST_ID + "=" + musicListId,
                null);

        // 删除musiclist表中的关于指定歌单的数据
        int deleteMusicListResult = context.getContentResolver().delete(
                MusicListProvider.CONTENT_URI,
                MusicList.MUSIC_LIST_ID + "=" + musicListId,
                null
        );
        return deleteMusicInMusicListResult >= 0 && deleteMusicListResult > 0;
    }

    /**
     * 获取指定歌单的封面，如果歌单不为空，则将歌单中的第一首歌的专辑封面作为歌单封面，如果歌单为空，则将
     * 默认图片作为专辑封面。
     *
     * @param context       上下文对象
     * @param musicListName 指定歌单名称
     * @return 返回歌曲封面的bitmap对象
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public Bitmap getMusicListCover(Context context, String musicListName) {
        Bitmap bitmap;
        // 查询歌单中的歌曲id
        int musicListId = getMusicListIdByName(context, musicListName);
        Log.i("==============", "歌单名称" + musicListName);

        if (musicListId == NO_SUCH_MUSIC_LIST) {
            return null;
        }
        Cursor cursor = context.getContentResolver().query(
                MusicAndMusicListProvider.CONTENT_URI,
                null,
                MusicAndMusicList.KEY_MUSIC_LIST_ID + "=" + musicListId,
                null, null
        );
        // 歌单中没有音乐时设置默认封面
        if (cursor == null || cursor.getCount() == 0 || !cursor.moveToFirst()) {
            Log.i("==============", "歌单中没有音乐");
            BitmapDrawable bitmapDrawable = (BitmapDrawable) context.getDrawable(R.drawable.music_icon);
            assert bitmapDrawable != null;
            bitmap = bitmapDrawable.getBitmap();
            return bitmap;
        }
        cursor.moveToFirst();
        // 获取歌单第一首个音乐的专辑封面
        String musicId = cursor.getString(cursor.getColumnIndex(MusicAndMusicList.KEY_MUSIC_ID));
        cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media.DATA},
                MediaStore.Audio.Media._ID + "=" + musicId,
                null, null
        );
        if (cursor == null || cursor.getCount() == 0 || !cursor.moveToFirst()) {
            Log.i("==============", "没有在媒体库中找到该音乐");
            BitmapDrawable bitmapDrawable = (BitmapDrawable) context.getDrawable(R.drawable.music_icon);
            assert bitmapDrawable != null;
            bitmap = bitmapDrawable.getBitmap();
            return bitmap;
        }
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
        // ======== 获取专辑封面(begin) ===================//
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] data = retriever.getEmbeddedPicture();
        if (data != null) {
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        } else {
            Log.i("================", "设置默认专辑封面");
            BitmapDrawable bitmapDrawable = (BitmapDrawable) context.getDrawable(R.drawable.music_icon);
            assert bitmapDrawable != null;
            bitmap = bitmapDrawable.getBitmap();
        }
        cursor.close();
        return bitmap;
    }

    /**
     * 查询所有艺术家列表
     *
     * @param context 上下文对象
     * @return 艺术家名称列表
     */
    public List<String> getArtistsNameOfLocalMusic(Context context) {
        List<String> artistsNameList = new ArrayList<>();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media.ARTIST},
                null, null, null
        );
        if (cursor == null) {
            return artistsNameList;
        }
        while (cursor.moveToNext()) {
            String artistName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            if (!artistsNameList.contains(artistName)) {
                artistsNameList.add(artistName);
            }
        }
        cursor.close();
        return artistsNameList;
    }

    /**
     * 查询某个艺术家的所有歌曲
     *
     * @param context    上下文对象
     * @param artistName 艺术家名称
     * @return artistName的所有单曲
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public List<Music> getMusicListOfSpecifiedArtist(Context context, String artistName) {
        List<Music> musicList = new ArrayList<>();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null,
                MediaStore.Audio.Media.ARTIST + "=" + "\"" + artistName + "\"",
                null, null
        );
        if (cursor == null) {
            return musicList;
        }
        while (cursor.moveToNext()) {
            Music music;
            String id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));

            // ======== 获取专辑封面(begin) ===================//
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                retriever.setDataSource(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
            byte[] data = retriever.getEmbeddedPicture();
            Bitmap bitmap;
            if (data != null) {
                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            } else {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) context.getDrawable(R.drawable.album);
                assert bitmapDrawable != null;
                bitmap = bitmapDrawable.getBitmap();
            }
            music = new Music(id, name, artist, path, bitmap);
            Log.i("===================", music.getName());
            musicList.add(music);
        }
        cursor.close();
        return musicList;
    }
}
